/**
 * _开头的方法表示私有方法
 */
const db = wx.cloud.database();
const _ = db.command;
const tabel = "infectedLocations";
let mapCtx;
import { getDistance } from '../../utils/util.js';
import { Config } from '../../utils/config.js';
Page({
  data: {
    latitude: Config.defaultLocation.latitude,
    longitude: Config.defaultLocation.longitude,
    scale: 4,
    index: "0",
    showSearch: false,
    barAnimationData: {},
    city: Config.defaultCity,
    circles: [],
    loading: false,
    tips: [],
    markers: [],
    list: [],
    infectInfo: null,
    showInfectInfo: false,
    subscribes: [],
    showSubscribe: false,
    showModal: false,
    first: false,
    showEntrench: false
  },
  onLoad() {
    this._loadData();
  },
  onReady: function () {
    let that = this;
    try {
      mapCtx = wx.createMapContext('map');
    } catch (error) {
      console.error(error);
    }
  },
  //做位置获取权限处理并加载数据
  _loadData() {
    let that = this;
    this._getSubscribe();
    wx.getLocation({
      type: "gcj02",
      success(res) {
        if (res.errMsg == "getLocation:ok") {
          let circles = [];
          circles.push({
            latitude: res.latitude,
            longitude: res.longitude,
            fillColor: '#33ffff36',
            color: '#33ffff36',
            radius: 2000
          })
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            scale: 12,
            index: "1",
            circles: circles,
            first: true
          })
          that._geocode();
        }
      },
      fail(err) {
        wx.showModal({
          title: '授权被拒绝',
          content: '请在设置页手动打开位置授权',
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(res) {
                  if (res.errMsg == "openSetting:ok") {
                    if (res.authSetting['scope.userLocation']) {
                      that._loadData();
                    }
                  }
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  //bar点击事件
  barChange({ currentTarget }) {
    this._modifyBar(currentTarget.dataset.index);
  },
  //bar切换处理
  _modifyBar(index) {
    switch (index) {
      case "1":
        this._hideSearch();
        this.setData({
          showSubscribe: false,
          showInfectInfo: false,
          showEntrench: false
        })
        this._loadData();
        break;
      case "2":
        this.setData({
          showSubscribe: true,
          showInfectInfo: false,
          showSearch: false,
          showEntrench: false,
          index: index
        })
        this._showSubscribe();
        break;
      case "3":
        this.setData({
          index: index,
          showSubscribe: false,
          showInfectInfo: false,
          showSearch: false,
          showEntrench: true
        })
        this._showEntrench();
        break;
      default:
        break;
    }
  },
  //自我防护显示处理
  _showEntrench() {
    let showEntrench = this.data.showEntrench,
      barHeight = showEntrench ? "800rpx" : "268rpx";
    let barAnimation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.barAnimation = barAnimation
    barAnimation.height(barHeight).step();
    this.setData({
      barAnimationData: barAnimation.export()
    })
  },
  //订阅历史显示处理
  _showSubscribe() {
    let showSubscribe = this.data.showSubscribe,
      barHeight = showSubscribe ? "800rpx" : "268rpx";
    let barAnimation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.barAnimation = barAnimation
    barAnimation.height(barHeight).step();
    this.setData({
      barAnimationData: barAnimation.export()
    })
  },
  //地图可视范围变更事件
  regionChange(e) {
    if (e.type == "end") {
      this._getInfected();
    }
  },
  //marker点击事件
  markerTap({ markerId }) {
    let list = this.data.list,
      latitude = this.data.latitude,
      longitude = this.data.longitude,
      index = this.data.index,
      that = this;
    if(index != "1"){
      return false;
    }
    list.forEach(item => {
      if (item._id == markerId) {
        let coordinates = JSON.parse(item.location).coordinates;
        item.distance = getDistance(latitude, longitude, coordinates[1], coordinates[0], 2);
        that.setData({
          infectInfo: item,
          showInfectInfo: true,
          showSearch: false,
        })
        that._showInfectInfo();
      }
    })
  },
  //感染信息显示处理
  _showInfectInfo() {
    let showInfectInfo = this.data.showInfectInfo,
      barHeight = showInfectInfo ? "500rpx" : "268rpx";
    let barAnimation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.barAnimation = barAnimation
    barAnimation.height(barHeight).step();
    this.setData({
      barAnimationData: barAnimation.export()
    })
  },
  //隐藏感染信息
  hideInfectInfo() {
    this.setData({
      showInfectInfo: false,
      infectInfo: null
    })
    this._showInfectInfo();
  },
  //搜索状态变更
  searchChange() {
    this.setData({
      tips: [],
      showInfectInfo: false,
      showSubscribe: false,
      showEntrench: false,
      showSearch: !this.data.showSearch
    })
    this._showSearch();
  },
  //输入提示
  inputtips({ detail }) {
    let data = this.data, that = this;
    this.setData({ tips: [] })
    if (detail.value.length > 0) {
      this.setData({ loading: true })
      wx.cloud.callFunction({
        name: 'inputtips',
        data: {
          latitude: data.latitude,
          longitude: data.longitude,
          city: data.city,
          keyword: detail.value
        },
        complete: res => {
          this.setData({ loading: false })
          if (res.errMsg == "cloud.callFunction:ok") {
            let result = res.result;
            if (result != null) {
              that.setData({
                tips: result.tips
              })
              that._isSubscribe();
            }
          }
        }
      })
    }
  },
  //取消订阅
  cancelSubscribe({ currentTarget }) {
    const id = currentTarget.dataset.id;
    let that = this;
    wx.showNavigationBarLoading();
    db.collection('messages').where({
      _id: id
    }).remove().then(res => {
      wx.hideNavigationBarLoading();
      if (res.errMsg == "collection.remove:ok") {
        wx.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 2000,
        });
        that._getSubscribe();
      } else {
        console.log(res);
        wx.showToast({
          title: '取消失败',
          icon: 'none',
          duration: 2000,
        });
      }
    }).catch(err => {
      wx.hideNavigationBarLoading();
      console.log(err);
      wx.showToast({
        title: '取消失败',
        icon: 'none',
        duration: 2000,
      });
    });
  },
  //订阅处理
  onSubscribe({ currentTarget }) {
    let tips = this.data.tips, tip = null, that = this;
    const id = currentTarget.dataset.id;
    tips.forEach(item => {
      if (item.id == id) {
        tip = item;
      }
    })
    if (tip == null) {
      return false;
    }
    wx.requestSubscribeMessage({
      tmplIds: Config.lessonTmplIds,
      success(res) {
        let tmplIds = [];
        if (res.errMsg === 'requestSubscribeMessage:ok') {
          for (let key in res) {
            if (res[key] == "accept") {
              tmplIds.push(key)
            }
          }
          if (tmplIds.length == 0) {
            return false;
          }
          wx.showNavigationBarLoading();
          wx.cloud.callFunction({
            name: 'subscribe',
            data: {
              name: tip.name,
              district: tip.district,
              location: tip.location,
              tipId: tip.id,
              templateId: tmplIds[0],
            },
          }).then(() => {
            wx.hideNavigationBarLoading();
            that._getSubscribe();
            wx.showToast({
              title: '订阅成功',
              icon: 'success',
              duration: 2000,
            });
          }).catch(() => {
            wx.hideNavigationBarLoading();
            wx.showToast({
              title: '订阅失败',
              icon: 'none',
              duration: 2000,
            });
          });
        }
      },
    });
  },
  //地理编码
  _geocode() {
    let latitude = this.data.latitude,
      longitude = this.data.longitude,
      that = this;
    wx.cloud.callFunction({
      name: 'geocode',
      data: {
        location: `${longitude},${latitude}`,
      },
      complete: res => {
        if (res.errMsg == "cloud.callFunction:ok") {
          let result = res.result;
          if (result != null) {
            if (result.addressComponent.citycode) {
              that.setData({
                city: result.addressComponent.citycode
              })
            }
          }
        }
      }
    })
  },
  //搜索页显示处理
  _showSearch() {
    let showSearch = this.data.showSearch,
      index = this.data.index,
      barHeight = showSearch ? "100%" : "268rpx";
    let barAnimation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.barAnimation = barAnimation
    barAnimation.height(barHeight).step();
    this.setData({
      barAnimationData: barAnimation.export()
    })
    if (!showSearch && index != "1") {
      this._modifyBar(index)
    }
  },
  //隐藏搜索页
  _hideSearch() {
    let barAnimation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.barAnimation = barAnimation
    barAnimation.height("268rpx").step();
    this.setData({
      showSearch: false,
      barAnimationData: barAnimation.export()
    })
  },
  //获取感染数据
  _getInfected() {
    let that = this, first = this.data.first;
    mapCtx.getCenterLocation({
      success(res) {
        if (res.errMsg == "getMapCenterLocation:ok") {
          wx.showNavigationBarLoading();
          db.collection(tabel).where({
            location: _.geoNear({
              geometry: db.Geo.Point(res.longitude, res.latitude)
            })
          }).get().then(res => {
            wx.hideNavigationBarLoading();
            if (res.errMsg == "collection.get:ok") {
              let data = res.data, markers = []
              data.forEach(item => {
                let coordinates = JSON.parse(item.location).coordinates
                markers.push({
                  iconPath: "/images/icon.png",
                  latitude: coordinates[1],
                  longitude: coordinates[0],
                  width: 30,
                  height: 30,
                  id: item._id
                })
              })
              that.setData({ markers: markers, list: data, first: false });
              if (first){
                that.nearby()
              }
            }
          }).catch(err => {
            wx.hideNavigationBarLoading();
            console.error(err)
          })
        }
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  //获取订阅数据
  _getSubscribe() {
    let that = this, showSearch = this.data.showSearch;
    wx.cloud.callFunction({
      name: 'mySubscribe',
      complete: res => {
        if (res.errMsg == "cloud.callFunction:ok") {
          let result = res.result;
          if (result != null) {
            that.setData({
              subscribes: result
            })
            if (showSearch) {
              that._isSubscribe();
            }
          }
        }
      }
    })
  },
  //判断地址是否被订阅
  _isSubscribe() {
    let subscribes = this.data.subscribes, tips = this.data.tips;
    tips.forEach(t => {
      t.isSubscribe = false;
      subscribes.forEach(s => {
        if (t.id == s.tipId) {
          t.isSubscribe = true;
        }
      })
    })
    this.setData({
      tips: tips
    })
  },
  touchHandler(){
    return;
  },
  //附近1公里内有感染信息时弹出提示
  nearby() {
    let list = this.data.list,
      latitude = this.data.latitude,
      longitude = this.data.longitude,
      infectInfo = list[0];
    let coordinates = JSON.parse(infectInfo.location).coordinates;
    let distance = getDistance(latitude, longitude, coordinates[1], coordinates[0], 2);
    if (distance <= 1) {
      this.setData({
        showModal: true,
        infectInfo: infectInfo
      })
    }
  },
  //隐藏提示
  hideModal(){
    this.setData({
      showModal: false
    })
  }
})